<?php
class UsersController extends AppController{
	var $name = 'Users';
	var $view = 'Theme';
    var $theme = HOST;
	var $components = array( 'Auth','Session','RequestHandler','Email','Cookie','CompCms','Password');
    var $permissions = array();
      
	public function beforeFilter(){
		parent::beforeFilter();
		$this->Auth->autoRedirect = false;
		$this->Auth->fields = array('username' => 'email', 'password' => 'password');	
			
	}
	
	public function beforeRender(){
		parent::beforeRender();
	}

    function login(){
    	if(!empty($this->data)){
    		$this->Auth->login($this->data);
    		$manager = $this->User->findById($this->Auth->user('manager_id'));
    		$this->Session->write("Manager",$manager);
    		$this->redirect($this->Auth->redirect());
    	}
    }
    
    function logout() {
        $this->redirect($this->Auth->logout());
    }
    
	function register() {
	    if(!empty($this->data)) {
		        $this->User->create();
		        if($this->User->save($this->data)) {
		            // send signup email containing password to the user
		            $this->Auth->login($this->data);
		    }
		}
	}
	
	public function new_password(){
		
    	if(!empty($this->data) && isset($this->data['User']['email'])){
    		$user = $this->User->findByEmail($this->data['User']['email']);
    		if(!is_array($user)){
    			$this->Session->setFlash(__("Podano zly adres e-mail.",true),'flash_error');
    			$this->redirect($this->referer());
    		}
    		$new_password = $this->Password->get();
    		$user['User']['password'] = $this->Auth->password($new_password);
    		$this->User->id = $user['User']['id'];
    		if($this->User->save($user)){  
    			$user['User']['password'] = $new_password;
    			$this->data = $user;	
		    	$this->Email->to = $user['User']['email']; 
//		        $this->Email->bcc = array('bok@21w.pl');
		        $this->Email->subject = __("Wygenerowano nowe haslo dla strony ",true).$_SERVER['HTTP_HOST']; 
		        $this->Email->replyTo = $user['User']['email']; 
		        $this->Email->from = $_SERVER['HTTP_HOST'].' <bok@21w.pl>'; 
		        $this->Email->template = 'new-password'; 
		        $this->Email->sendAs = 'both'; // text; html; both;

		        if ( $this->Email->send() ) { 
		            $this->Session->setFlash(__("Nowe haslo zostalo wyslane na Twoj adres e-mail.",true),'flash_succes'); 
		        } else { 
		            $this->Session->setFlash(__("Haslo zostalo wygenerowane ale wystapil blad w dostarczeniu go na adres uzytkowanika",true),'flash_error'); 
		        }
		        $this->redirect($this->referer());
    		}
    	}
    }
}